/*
 * Copyright (C) 2021. Dylan Cai
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.price.sample.ui

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.price.common.extend.cacheDirPath
import com.price.common.extend.compressImageByte
import com.price.common.extend.getBitmapFromLocalPath
import com.price.common.extend.saveBitmapFile
import com.price.common.extend.startActivity
import com.price.common.extend.toPath
import com.zp.common.R

class PictureActivity : AppCompatActivity() {


  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_picture)
    val imageView:ImageView=findViewById(R.id.imageView)

    intent.getParcelableExtra<Bitmap>("bitmap")?.let {
      imageView.setImageBitmap(it)
    }
    intent.getStringExtra("uri")?.let {
      val bitmap=Uri.parse(it).toPath()?.getBitmapFromLocalPath()
      val byteArray=bitmap?.compressImageByte()
      if(byteArray!=null) {
        val dctBit = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
        val path = dctBit?.saveBitmapFile("$cacheDirPath/${System.currentTimeMillis()}.jpg")
        path?.let {
          Glide.with(this).load(path).into(imageView)
        }
      }
    }
  }

  companion object {
    fun start(uri: Uri) = startActivity<PictureActivity>("uri" to uri.toString())

    fun start(bitmap: Bitmap) = startActivity<PictureActivity>("bitmap" to bitmap)
  }
}